package com.example.demo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Copyright © 合生活. All rights reserved.
 *
 * @Title: TestUrl
 * @Prject: ttc
 * @Package: com.feejson.ttc.util
 * @Description:
 * @author: feejson
 * @date: 2019-06-20 15:34
 * @version: V1.0
 */
public class TestUrl {

    private static final Logger logger = LoggerFactory.getLogger(TestUrl.class);
    public static  Map<String,String> CACHE = Maps.newHashMap();

    public static void main(String[] args) throws Exception {
        //解析输出
//        analyzeAllExercises("婚姻");
        //拉取写入
//        pullAllTypesOfExercises();

//        changeVodeDone("000000");
//        changeVodeDone("000000");
//        changeVodeDone("000000");


    }

    /**
     * 解析全部习题
     */
    public static String analyzeAllExercises(String yourSearchTermText) throws Exception {

        List<RightBean> rightBeansAll = Lists.newArrayList();
        for (int i = 1; i < 4; i++) {
            String exerciseContent = CACHE.get(String.valueOf(i));
            List<RightBean> rightBeans = analyticalExercises(exerciseContent, yourSearchTermText);
            rightBeansAll.addAll(rightBeans);
        }

        StringBuilder stringBuilder = new StringBuilder();
        for (RightBean bean:rightBeansAll) {
            System.out.println(bean.toString());
            stringBuilder.append("|--------------------------------------------------------------|\n");
            stringBuilder.append(" \t" + bean.toString());
            stringBuilder.append("|--------------------------------------------------------------|\n");
            stringBuilder.append("\n\n");
        }

        return  stringBuilder.toString();
    }

    /**
     * 拉取全部类型习题
     */
    public static void pullAllTypesOfExercises() throws Exception {
        zuoti("1");
        Thread.sleep(1000);
        zuoti("2");
        Thread.sleep(1000);
        zuoti("3");
    }
    /**
     * 解析练习题
     */
    public static List<RightBean> analyticalExercises(String content,String yourSearchTermText) {
        List<RightBean> list = Lists.newArrayList();
        JSONObject k = JSON.parseObject(content);
        JSONArray result = k.getJSONArray("result");
        result.forEach(p -> {
            ResultBean resultBean = JSON.parseObject(p.toString(), ResultBean.class);
            //包含你的搜索
            if (resultBean.getTitle().contains(yourSearchTermText)){
                List<String> correctAnswer = Lists.newArrayList();
                resultBean.getAnswer().stream()
                        .filter(aaaa -> resultBean.getRight().contains(String.valueOf(aaaa.getCode())))
                        .forEach(it -> {
                            correctAnswer.add("\n\t正确选项 --> " +it.getTitle());
                        });
                RightBean rightBean = new RightBean("题目 --> " + resultBean.getTitle(),"\n\t全部选项 --> " + resultBean.getAnswer().toString(),correctAnswer);
                list.add(rightBean);
            }
//            System.out.println("题目  " + resultBean.getTitle());
//            System.out.println();
//            System.out.println("全部选项  " + resultBean.getAnswer());
//            System.out.println();

//            resultBean.getAnswer().stream()
//                    .filter(aaaa -> resultBean.getRight().contains(String.valueOf(aaaa.getCode())))
//                    .forEach(it -> {
//                        System.out.println("正确选项   " + it.getTitle());
//                    });
//            System.out.println(resultBean.getRight());
        });
//        System.out.println(result);

        return  list;
    }

    /**
     * 读取练习题并写入文件 fromType 习题类型 1 2  3
     */
    public static void zuoti(String fromType) {
        Map<String, String> map = new HashMap<>();
        map.put("userId", "000000");
        // 1 2 3
        map.put("exercisesType", fromType);
        map.put("fromType", "0");
        String taskQuery = HttpRequest
                .post("http://edu.zxietong.com:81/xtedu/api/exercises/getExercise").form(map)
                .body();
        System.out.println(taskQuery);
        CACHE.put(fromType,taskQuery);
    }


    public static  Random random = new Random();
    /**
     * 一次学完全部视频 workId 工号
     */
    public static String changeVodeDone(String workId) {
        StringBuilder res = new StringBuilder();
        Integer all = 0;
        Map<String, String> map = new HashMap<>();
        map.put("workId", workId);
        map.put("year", "2020");
        String taskQuery = HttpRequest
                .post("http://edu.zxietong.com:81/xtedu/api/studytask/getStudyTaskList").form(map)
                .body();
        JSONObject taskQueryObj = JSON.parseObject(taskQuery);
        JSONArray data = taskQueryObj.getJSONArray("data");
        if (data.isEmpty() | data.size() <= 0) {
            return "拉取任务失败！";
        }
        for (Object p:data){
            JSONObject bean = (JSONObject) p;
            String m = bean.getString("month");
            int month = Integer.valueOf(m);
            int monthValue = LocalDate.now().getMonthValue();
            if (month == monthValue) {
                String id = bean.getString("id");
                Map<String, String> taskCourseQueryParam = new HashMap<>();
                taskCourseQueryParam.put("taskId", id);
                taskCourseQueryParam.put("workId", workId);
                String taskCourseQuery = HttpRequest
                        .post(" http://edu.zxietong.com:81/xtedu/api/studytask/getCoursesOfTask")
                        .form(taskCourseQueryParam).body();
                JSONObject videoBelowTheCourseObj = JSON.parseObject(taskCourseQuery);
                JSONArray videoBelowTheCoursedata = videoBelowTheCourseObj.getJSONArray("data");
                System.out.println(workId+"视频学习:" + taskCourseQuery);
                for (Object object : videoBelowTheCoursedata) {
                    JSONObject course = (JSONObject) object;
                    String videoId = course.getString("id");
                    String title = course.getString("title");
                    String hasComplete = course.getString("hasComplete");
                    if ("1".equals(hasComplete)){
                        logger.info("已完成学习！");
                        continue;
                    }
                    Map<String, String> videoBelowTheCourseParam = new HashMap<>();
                    videoBelowTheCourseParam.put("courseId", videoId);
                    String videoBelowTheCourse = HttpRequest
                            .post("http://edu.zxietong.com:81/xtedu/api/course/getItemList")
                            .form(videoBelowTheCourseParam).body();
                    System.out.println(title + "Item:" + videoBelowTheCourse);
                    JSONObject studyOne = JSON.parseObject(videoBelowTheCourse);
                    JSONArray studyOneJSONArray = studyOne.getJSONArray("data");
//                    try {
//                        int i = random.nextInt(5)+1;
//                        all += i*60;
//                        logger.info(workId+"学习视频随机间隔时间:" + i + "分钟");
//                        Thread.sleep(i * 1000 * 60);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                    for (Object o : studyOneJSONArray) {
                        JSONObject s = (JSONObject) o;
                        String name = s.getString("name");
                        String itemId = s.getString("id");
                        String itemTime = s.getString("shichang");
                        try {
                            int studyTime = Integer.parseInt(itemTime);
                            all += studyTime;
                            logger.info(workId+name + "学习时间:" + studyTime + "秒");
//                            Thread.sleep(studyTime * 1000);
                            Map<String, String> param = new HashMap<>();
                            param.put("itemId", itemId);
                            param.put("itemTime", itemTime);
                            param.put("studyTime", itemTime);
                            param.put("userId", workId);
                            String recordLearningRecord = HttpRequest
                                    .post("http://edu.zxietong.com:81/xtedu/api/course/setUserStudyHistory")
                                    .form(param).body();
                            logger.info(JSON.toJSONString(recordLearningRecord));
                            res.append(recordLearningRecord);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        logger.info(workId+"完成视频学习总时长"+all);
        return res.toString();
    }

//        http://edu.zxietong.com:81/xtedu/api/studytask/getStudyTaskList 任务查询
//        workId	000000
//        year	2019
//        http://edu.zxietong.com:81/xtedu/api/studytask/getCoursesOfTask 任务课程查询
//        taskId	ff8080816b4a1529016b4c53d955004b
//        workId	000000
//
//        http://edu.zxietong.com:81/xtedu/api/course/getCourseDetail
//        courseId	ff8080816af83ff4016af98572090052
//        workId	000000
//
//        http://edu.zxietong.com:81/xtedu/api/course/getItemList 课程下面的视频
//        courseId	ff8080816af83ff4016af98572090052
//        http://edu.zxietong.com:81/xtedu/api/course/setUserStudyHistory 记录学习记录
//
//        itemId	ff8080816afce623016afd000c06000f
//        itemTime	986
//        studyTime	17
//        userId	000000
//
//        http://edu.zxietong.com:81/xtedu/api/exercises/getExercise  获取所有 题目
//
//        userId	000000
//        exercisesType	1
//        fromType	0
//
//        http://edu.zxietong.com:81/xtedu/api/exercises/setExerciseResult
//        userId	000000
//        exercisesId	402840a76b543509016b54b5d1e10294
//        answer	0
//        trueanswers	1
//        type	0
//        fromType	0
//        isTrue	0

    /**
     * 获取视频学习状态
     */
    public static JSONObject getVideoStudyStatus(String workId,Integer year,Integer month) {
        Map<String, String> map = new HashMap<>();
        map.put("workId", workId);
        map.put("year", String.valueOf(year));
        String taskQuery = HttpRequest
                .post("http://edu.zxietong.com:81/xtedu/api/studytask/getStudyTaskList").form(map)
                .body();
        JSONObject taskQueryObj = JSON.parseObject(taskQuery);
        JSONArray data = taskQueryObj.getJSONArray("data");
        if (data.isEmpty() | data.size() <= 0 ){
            return null;
        }
        JSONObject bean = new JSONObject();
        for (Object o:data){
            JSONObject object = (JSONObject) o;
            String a = object.getString("month");
            int s = Integer.valueOf(a);
            int monthValue = LocalDate.now().getMonthValue();
            if (s == month){
                String id = object.getString("id");
                Map<String, String> param = new HashMap<>();
                param.put("taskId", id);
                param.put("workId", workId);
                String course = HttpRequest
                        .post("http://edu.zxietong.com:81/xtedu/api/studytask/getCoursesOfTask")
                        .form(param).body();
                bean = JSON.parseObject(course);
                break;
            }
        }
        return  bean;
    }

}
